﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Data;

namespace TCC.ControleFluxoDeCaixa.Apresentacao.ResourcesDictionaries.Converters
{
    public class EnumToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value.GetType().IsEnum)
            {
                var desc = GetDescription((Enum) value);
                if (desc != null) return desc;

                return Regex.Replace(value + "", "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType.IsEnum)
            {
                var name =  Enum.GetNames(targetType).SingleOrDefault(s=> String.Equals(s, (value + "").Replace(" ",""), StringComparison.CurrentCultureIgnoreCase));
                if (name != null)
                    return Enum.Parse(targetType, name, false);
            }
            return value;
        }

        private string GetDescription(Enum value)
        {
            if (value == null) return null;
            
            var type = value.GetType();
            var field = type.GetField(value.ToString());
            if (field != null)
            {
                var attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null) return attr.Description;
            }
            return null;
        }
    }
}